﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using RayDen.GLPlayground;
using RayDen.Library.Data.Xml;
using RayDen.Library.Entity.Frames;
using RayDen.Library.Entity.Interface;
using RayDen.RayEngine;

namespace Eucalyptus
{
    public class AppController
    {
        public FrameDescription Frame { get; set; }
        private LogController logController;
        private TexturedQuadWindow window;
        internal RayEngineConfiguration re;
        public AppController()
        {
            GlobalConfiguration.Instance.OpenConfig(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Global.Config.xml");
        }


        public void InitLog(TextBoxBase txt)
        {
            this.logController = new LogController(txt);
        }

        public void LoadFrame(string frameName)
        {
            using (var frameFile = new FileStream(frameName, FileMode.Open, FileAccess.Read))
            {
                using (var reader = new StreamReader(frameFile))
                    this.Frame = (FrameDescription)SerializationService.Deserialize(reader.ReadToEnd(), typeof(FrameDescription));
            }
        }

        public async Task<int> StartRenderer()
        {
            GlobalConfiguration.Instance.SaveConfig(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\Global.Config.xml");
            re =
                //new Renderer();
                //new EngineConfig();
                new RayEngineConfiguration();
            return await Task.Factory.StartNew(() =>
            {
                //new MegaRay.Renderer();

                //(re as RayEngineConfiguration).OpenSceneConfiguration(@"F:\Dev\Frames\Config\cornell.sceneconfig");
                re.OpenFrame(this.Frame);

                using (var example = new TexturedQuadWindow(re))
                //using (var example = new MainWindow(re))
                {
                    this.window = example;
                    example.Run(0.067);
                }

                return 1;
            });
        }

        public async Task<int> StopRenderer()
        {
            return await Task.Factory.StartNew(() =>
            {
                re.Interrupt();
                window.Close();
                return 0;
            });
        }
    }
}
